package orm

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"sanrenx.com/xyxf/pkg/setting"
	"time"
)

var DB *gorm.DB

const (
	OrderByHotDesc = "hot desc"
	OrderByIdAsc   = "id asc"
	OrderByIdDesc  = "id desc"
	OrderByNewDesc = "created_at desc"
)

type Model struct {
	ID uint64 `gorm:"primary_key" json:"id" form:"id"`

	CreatedAt LocalTime      `json:"createdAt,omitempty"`
	UpdatedAt LocalTime      `json:"updatedAt,omitempty"`
	DeletedAt gorm.DeletedAt `json:"deletedAt,omitempty"`
}

type Column struct {
	ID        uint64
	Hot       int
	CreatedAt LocalTime
}

// Setup initializes the database instance
func Setup() {
	var err error
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		setting.DatabaseSetting.User,
		setting.DatabaseSetting.Password,
		setting.DatabaseSetting.Host,
		setting.DatabaseSetting.Name)

	if setting.ServerSetting.Debug {
		DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
			SkipDefaultTransaction: true, //禁用默认事务
			NamingStrategy: schema.NamingStrategy{
				TablePrefix:   setting.DatabaseSetting.TablePrefix, // 表名前缀
				SingularTable: true,                                // 使用单数表名
				NameReplacer:  nil,
			},
			Logger: logger.New(
				log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
				logger.Config{
					SlowThreshold: time.Second, // 慢 SQL 阈值
					LogLevel:      logger.Info, // Log level
					Colorful:      true,        // 禁用彩色打印
				},
			),
		})
	} else {
		DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
			SkipDefaultTransaction: true, //禁用默认事务
			NamingStrategy: schema.NamingStrategy{
				TablePrefix:   setting.DatabaseSetting.TablePrefix, // 表名前缀
				SingularTable: true,                                // 使用单数表名
				NameReplacer:  nil,
			},
		})
	}

	if err != nil {
		log.Fatalf("models.Setup err: %v", err)
	}
}
